package xusage.cumulus.log4j.listener;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Hashtable;

import javax.servlet.ServletContext;

import org.apache.log4j.Hierarchy;

public abstract class CumulusLog4jServer {

	private static final String SERVER_PORT_PARAM = "log4jServerPort";
	private static final int DEFAULT_SERVER_PORT = 4560; 
		
	private static int port;
	private static ServerSocket serverSocket;
	private static boolean shutdown;
	private static Hashtable<String, Hierarchy> hierarchyMap;
	
	public static void initServer(ServletContext servletContext) {
		String port = servletContext.getInitParameter(SERVER_PORT_PARAM);
		try {
			CumulusLog4jServer.port = Integer.parseInt(port);
		}
		catch (Exception ex) {
			CumulusLog4jServer.port = DEFAULT_SERVER_PORT;
		}
		try {
			serverSocket = new ServerSocket(CumulusLog4jServer.port);
			shutdown = false;
			new Log4jServerThread().start();
		}
		catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static void shutdownServer(ServletContext servletContext) {
		try {
			serverSocket.close();
		}
		catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	private static class Log4jServerThread extends Thread {
		
		public void run() {
			while(!shutdown) {
				try {
					Socket socket = serverSocket.accept();					
					new Thread(new CumulusLog4jServerNode(socket, hierarchyMap)).start();
				}
				catch (IOException ex) {
					ex.printStackTrace();
				}
			}
		}
	}
}
